package com.pwt.service;

import com.pwt.common.CustomException;
import com.pwt.common.ResultPage;
import com.pwt.entity.Images;
import com.pwt.repository.ImagesRepository;
import com.pwt.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Images service层
 *
 * @author auto generated
 * @date 2021-12-20 20:58:51
 */
@Service
public class ImagesService {

    private ImagesRepository imagesRepository;

    public ImagesService(ImagesRepository imagesRepository) {
        this.imagesRepository = imagesRepository;
    }


    public ResultPage<Images> imagesPage(String name, String startTime, String endTime, Integer page, Integer limit,String serverPath){
        serverPath = serverPath+"/downLoadImages?id=";
        return this.imagesRepository.imagesPage(name,startTime,endTime,page,limit,serverPath);
    }


    public void downLoadImages(String id, HttpServletResponse response) throws CustomException, IOException {
        Images images = this.imagesRepository.getById(id);
        if(images == null){
            throw new CustomException("未查到图片信息！");
        }
        File file = new File(images.getPath());
        if(!file.exists()){
            throw new CustomException("图片已被删除！");
        }
        FileInputStream inputStream = null;
        try {
            String contentType= FileUtils.getContentType(images.getSuffixName());
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(images.getFileName() + images.getSuffixName(),"UTF-8"));
            inputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024*4];
            int length = -1;
            while ((length = inputStream.read(bytes, 0, 1024*4)) != -1) {
                response.getOutputStream().write(bytes, 0, length);
            }
            if(inputStream != null) inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null) inputStream.close();
        }

    }
}
